<?php
/**
 * @ClassName: BasicLogic
 * @Description: 基础逻辑
 * @author: wyaohu
 * @Date: 2025-07-23 15:22
 * @Version: V1.0.0
 */

namespace app\meituan\logic;

class BasicLogic
{
    protected $appkey = '2f40fe34835d45f8889f1ef80ea99075';//测试版
    protected $secret = 'H+B|PwC_E9RE{LuieH6L7Yu~8e-oh`z[8;Ald|5^F7ocZQZ!+lP/L/:q},45.]';//测试版
    protected $APIURL = "https://peisongopen.meituan.com/api";//API接口
    protected $version = '1.0';//版本号
    //请求头
    protected $header = array(
        'Accept: application/x-www-form-urlencoded',
        'Content-Type: application/x-www-form-urlencoded; charset=utf-8'
    );

    /**
     * 签名
     * @param $params
     * @param string $type
     * @return string
     */
    public function makeSign($params, string $type = '')
    {
        unset($params['sign']);//删除签名字段
        if ($type == 'img') {
            //图片上传特殊处理
            unset($params['image_data']);
        }
        ksort($params);//排序
        makelog("签名参数：\n" . json_encode($params, 320), "api/meituan/sign");
        $str = '';
        //参数拼接
        foreach ($params as $k => $v) {
            $str .= $k . $v;
        }
        //密钥拼接
        $str = $this->secret . $str;
        //加密
        return sha1($str);
    }

    /**
     * 验签
     * @param $params
     * @param string $type
     * @return bool
     */
    public function checkSign($params, string $type = '')
    {
        $sign = $params['sign'];
        unset($params['sign']);
        if ($type == 'img') {
            //图片上传特殊处理
            unset($params['image_data']);
        }
        ksort($params);
        makelog("验签参数：\n" . json_encode($params, 320), "api/meituan/sign");
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k . $v;
        }
        $str = $this->secret . $str;
        $sign2 = sha1($str);
        if ($sign == $sign2) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 图片上传
     * @param $image_name [图片文件名]
     * @param $image_data [图片内容]
     * @return bool|string
     */
    public function upload($image_name, $image_data)
    {
        $params = [
            'image_name' => $image_name,
            'image_data' => $image_data,
        ];
        $res = $this->curlRequest('/file/image/upload', $params);
        return $res;
    }

    /**
     * 发送请求
     * @param $url [请求的URL地址]
     * @param $data [请求的参数]
     * @param $ispost [是否采用POST形式]
     * @param $json [是否返回JSON格式]
     * @return bool|string
     */
    function curlRequest($url, $data = [], $ispost = true, $json = true)
    {
        // 补充公共参数
        $data['appkey'] = $this->appkey;//appkey
        $data['timestamp'] = time();//时间戳
        $data['version'] = $this->version;//版本号
        $data['sign'] = $this->makeSign($data);//签名

        $httpInfo = array();
        $ch = curl_init();
        //强制使用 HTTP/1.1
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        //在HTTP请求中包含一个"User-Agent: "头的字符串
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.95 Safari/537.36');
        //在发起连接前等待的时间，如果设置为0，则无限等待
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        //设置cURL允许执行的最长秒数 60秒
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        //设置获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            $method = "POST";
            //设置请求头
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->header);
            //设置post方式提交
            curl_setopt($ch, CURLOPT_POST, true);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 这个中文会被转码，所以不使用
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            //设置请求的url
            curl_setopt($ch, CURLOPT_URL, $this->APIURL . $url);
        } else {
            $method = "GET";
            if ($data) {
                // 拼接请求参数
                $params = "";
                foreach ($data as $key => $item) {
                    if (!$params) {
                        $params = "?" . $key . "=" . $item;
                    } else {
                        $params .= "&" . $key . "=" . $item;
                    }
                }
                curl_setopt($ch, CURLOPT_URL, $this->APIURL . $url . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $this->APIURL . $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);

        // 写入日志
        $log = "";
        $log .= "----------请求开始----------\n";
        $log .= "请求地址：" . $this->APIURL . $url . "\n";
        $log .= "请求方式：" . $method . "\n";
        $log .= "请求参数：" . json_encode($data, 320) . "\n";
        $log .= "请求结果：" . $response . "\n";
        $log .= "----------请求结束----------\n";
        makelog($log, "api/meituan");

        if ($json) {
            $res = json_decode($response, true);
            if (!isset($res['data'])) {
                $res['data'] = [];
            }
            return $res;
        }
        return $response;
    }

}